<script>
import {message} from "ant-design-vue";
import jumpHelper from "@/js/pageJumper";
import {getPhoneCode, resetPassword, signInPost, signUpPost} from "@/js/apiHelper";

export default {
  name: "SignInCom",
  data(){
    return{
      rememberMe:true,
      waitSeconds:60,
      sendCodeDisplay:{
        signUpEnable:true,
        signUpText:'发送短信验证码',
        signUpSeconds:0,
        resetPsdEnable:true,
        resetPsdText:'发送短信验证码',
        resetPsdSeconds:0
      },
      signMode:0, //0-登录 1-注册 2-找回密码
      signInData:{
        account:'',
        password:'',
      },
      signUpData:{
        account: '',
        password:'',
        checkPassword:'',
        code:'',
      },
      resetPasswordData:{
        account: '',
        password:'',
        checkPassword:'',
        code:'',
      }
    }
  },
  created() {
    // 在组件创建时，检查本地存储是否有保存的用户名和密码
    const savedUsername = localStorage.getItem('username');
    const savedPassword = localStorage.getItem('password');
    if (savedUsername && savedPassword) {
      // 如果有保存的用户名和密码，则填充到输入框中
      this.signInData.account = savedUsername;
      this.signInData.password = savedPassword;
    }
  },
  methods:{
    switchTo(mode){
      this.signMode = mode;
    },
    //发送验证码
    async sendCode(when){
      //检查手机号格式
      if (when === 0){
        //注册时
        if (!this.sendCodeDisplay.signUpEnable){
          return
        }
        const phoneNumberPattern = /^1\d{10}$/;
        if (!phoneNumberPattern.test(this.signUpData.account)){
          message.error('请输入正确格式的中国大陆手机号')
        }else{
          this.sendCodeCheck(0).then(response=>{
            if (response.success === 1){
              message.success('发送成功');
              this.sendCodeDisplay.signUpSeconds = this.waitSeconds;
              this.sendCodeDisplay.signUpEnable = false;
              this.disableSendCode(0);
            }else{
              message.error(response.message)
            }
          }).catch(e=>{
            message.error('发送失败：'+e)
          })
        }
      }else{
        //密码重置时
        if (!this.sendCodeDisplay.resetPsdEnable){
          return
        }
        const phoneNumberPattern = /^1\d{10}$/;
        if (!phoneNumberPattern.test(this.resetPasswordData.account)){
          message.error('请输入正确格式的中国大陆手机号');
        }else{
          this.sendCodeCheck(1).then(response=>{
            if (response.success === 1){
              message.success('发送成功');
              this.sendCodeDisplay.resetPsdSeconds = this.waitSeconds;
              this.sendCodeDisplay.resetPsdEnable = false;
              this.disableSendCode(1);
            }else {
              message.error(response.message)
            }
          }).catch(e=>{
            message.error('发送失败：'+e)
          })
        }
      }
    },
    async sendCodeCheck(mode){
      var phoneNum = '';
      if (mode === 0){
        phoneNum = this.signUpData.account;
      }else{
        phoneNum = this.resetPasswordData.account;
      }
      try {
        const response = await getPhoneCode(phoneNum, mode)
        return response.data;
      } catch (error) {
        message.error('向服务器发送POST请求失败：', error)
      }
    },
    disableSendCode(mode){
      if (mode ===0){
        //注册时
        this.sendCodeDisplay.signUpSeconds -= 1;
        this.sendCodeDisplay.signUpText = this.sendCodeDisplay.signUpSeconds + 's';
        if (this.sendCodeDisplay.signUpSeconds <= 0){
          setTimeout(()=>{
            this.sendCodeDisplay.signUpText = '发送短信验证码'
            this.sendCodeDisplay.signUpEnable = true;
          },1000);
        }else{
          setTimeout(()=>{
            this.disableSendCode(mode);
          },1000)
        }
      }else{
        //重设密码时
        this.sendCodeDisplay.resetPsdSeconds -= 1;
        this.sendCodeDisplay.resetPsdText = this.sendCodeDisplay.resetPsdSeconds + 's';
        if (this.sendCodeDisplay.resetPsdSeconds <= 0){
          setTimeout(()=>{
            this.sendCodeDisplay.resetPsdText = '发送短信验证码'
            this.sendCodeDisplay.resetPsdEnable = true;
          },1000);
        }else{
          setTimeout(()=>{
            this.disableSendCode(mode);
          },1000)
        }
      }
    },
    //登录
    async signInBtn(){
      const phoneNumberPattern = /^1\d{10}$/;
      if (!phoneNumberPattern.test(this.signInData.account)){
        message.error('请输入正确格式的中国大陆手机号');
        return
      }
      if (this.signInData.account.length <= 0 || this.signInData.password.length <= 0) {
        message.error('请输入完整的账号和密码');
      } else {
        const postResult = signInPost(this.signInData.account, this.signInData.password);
        postResult.then(response=>{
          if (response.data === 0){
            message.success('登录成功');
            //记住密码
            if (this.rememberMe){
              localStorage.setItem('username', this.signInData.account);
              localStorage.setItem('password', this.signInData.password);
            }else{
              localStorage.removeItem('username');
              localStorage.removeItem('password');
            }
            //页面跳转
            jumpHelper.jumpToUserPage()
            this.signInData = {
              account:'',
              password:'',
            }
          }else if (response.data === 1){
            message.error('账号还未注册');
          }else if(response.data === 2){
            message.error('密码错误');
          }else if(response.data === 3){
            message.error('账号被封禁');
          }
        }).catch(e=>{
          console.log(e)
          message.error('服务器响应错误，登陆失败');
        })
      }
    },
    //注册
    async signUpBtn() {
      if (this.signUpData.account.length < 1 || this.signUpData.password.length < 1 || this.signUpData.checkPassword.length < 1 || this.signUpData.code.length < 1) {
        message.error('输入不能为空');
        return false;
      }
      const phoneNumberPattern = /^1\d{10}$/;
      if (!phoneNumberPattern.test(this.signUpData.account)) {
        message.error('请输入正确格式的中国大陆手机号');
        return false;
      }
      if (!(this.signUpData.password === this.signUpData.checkPassword)){
        message.error('两次输入密码不一样');
        return false;
      }
      const postResult = signUpPost(this.signUpData.account, this.signUpData.password, 0, this.signUpData.code)
      postResult.then(response=>{
        if (response.data === 0){
          message.success('注册成功');
          this.signUpData = {
            account: '',
            password:'',
            checkPassword:'',
            code:'',
          };
        }else if(response.data === 1){
          message.error('账号已被注册');
        }else if (response.data === 2){
          message.error('验证码错误');
        }
      }).catch(e=>{
        message.error('注册失败，错误：'+ e)
      })
    },
    //重设密码
    async resetPasswordBtn() {
      if (this.resetPasswordData.account.length < 1 || this.resetPasswordData.password.length < 1 || this.resetPasswordData.checkPassword.length < 1 || this.resetPasswordData.code.length < 1) {
        message.error('输入不能为空');
        return false;
      }
      const phoneNumberPattern = /^1\d{10}$/;
      if (!phoneNumberPattern.test(this.resetPasswordData.account)) {
        message.error('请输入正确格式的中国大陆手机号');
        return false;
      }
      if (!(this.resetPasswordData.password === this.resetPasswordData.checkPassword)) {
        message.error('两次输入密码不一样');
        return false;
      }
      const postResult = resetPassword(this.resetPasswordData.account, 1, this.resetPasswordData.code, this.resetPasswordData.password)
      postResult.then(response=>{
        if (response.data === 0){
          message.success('重设密码成功');
          this.resetPasswordData = {
            account: '',
            password: '',
            checkPassword: '',
            code: '',
          };
        }else if(response.data === 1){
          message.error('账号还未注册');
        }else if (response.data === 2){
          message.error('验证码错误');
        }
      }).catch(e=>{
        message.error('重设密码失败，服务器响应：'+e)
      })
    },
    //第三方登录
    signInWithQQ(){
      message.warn('功能建设中')
    },
    signInWithWeChat(){
      message.warn('功能建设中')
    },
    signInWithTG(){
      message.warn('功能建设中')
    }
  },
}
</script>

<template>
  <div class="sign-container" >
    <!--登录-->
    <div v-if="signMode===0" class="sign-detail-container">
      <h1>登录</h1>
      <div class="line-container sign-in-line-container">
        <div class="sign-line">
          <a-input v-model:value="signInData.account" placeholder="请输入手机号">
            <template #prefix>
              <img src="@/assets/phone.png">
            </template>
          </a-input>
        </div>
        <div class="sign-line">
          <a-input-password type="password" v-model:value="signInData.password" placeholder="请输入密码">
            <template #prefix>
              <img src="@/assets/password.png">
            </template>
          </a-input-password>
        </div>
        <div class="sign-line">
          <!--记住密码未实现-->
          <a-checkbox v-model:checked="rememberMe" >记住我</a-checkbox>
        </div>
        <div class="sign-line">
          <button style="left: 0; transform: translate(0,88%); width: 100% " @click="signInBtn">开始</button>
        </div>
      </div>
      <div @click="switchTo(1)" class="link-text1">点击注册</div>
      <div @click="switchTo(2)" class="link-text2">忘记密码？点击重设</div>
      <div class="sign-in-other-container">
        <a-divider class="sign-divider" />
        <img @click="signInWithQQ" src="@/assets/QQ.png">
        <img @click="signInWithWeChat" src="@/assets/wechat.png">
        <img @click="signInWithTG" src="@/assets/telegram.png">
      </div>
    </div>
    <!--注册-->
    <div v-if="signMode===1" class="sign-detail-container">
      <h1>注册</h1>
      <div class="line-container sign-up-line-container">
        <div class="sign-line">
          <a-input v-model:value ="signUpData.account" placeholder="请输入手机号">
            <template #prefix>
              <img src="@/assets/phone.png">
            </template>
          </a-input>
        </div>
        <div class="sign-line">
          <a-input v-model:value ="signUpData.password" placeholder="请输入密码">
            <template #prefix>
              <img src="@/assets/password.png">
            </template>
          </a-input>
        </div>
        <div class="sign-line">
          <a-input v-model:value ="signUpData.checkPassword" placeholder="请确认密码">
            <template #prefix>
              <img src="@/assets/password.png">
            </template>
          </a-input>
        </div>
        <div class="sign-line">
          <div style="margin-right: 8px; white-space: nowrap">验证：</div>
          <a-input v-model:value ="signUpData.code" placeholder="请输入验证码">
            <template #prefix>
              <img src="@/assets/security.png">
            </template>
          </a-input>
        </div>
      </div>
      <div class="link-text1" @click="sendCode(0)">{{ sendCodeDisplay.signUpText }}</div>
      <div @click="switchTo(0)" class="link-text2">返回</div>
      <button @click="signUpBtn">确认</button>
    </div>
    <!--重设密码-->
    <div v-if="signMode===2" class="sign-detail-container">
      <h1>重设密码</h1>
      <div class="line-container">
        <div class="sign-line">
          <a-input v-model:value ="resetPasswordData.account" placeholder="请输入手机号">
            <template #prefix>
              <img src="@/assets/phone.png">
            </template>
          </a-input>
        </div>
        <div class="sign-line">
          <a-input v-model:value ="resetPasswordData.password" placeholder="请输入密码">
            <template #prefix>
              <img src="@/assets/password.png">
            </template>
          </a-input>
        </div>
        <div class="sign-line">
          <a-input v-model:value ="resetPasswordData.checkPassword" placeholder="请确认密码">
            <template #prefix>
              <img src="@/assets/password.png">
            </template>
          </a-input>
        </div>
        <div class="sign-line">
          <a-input v-model:value ="resetPasswordData.code" placeholder="请输入验证码">
            <template #prefix>
              <img src="@/assets/security.png">
            </template>
          </a-input>
        </div>
      </div>
      <div class="link-text1" @click="sendCode(1)">{{ sendCodeDisplay.resetPsdText }}</div>
      <div @click="switchTo(0)" class="link-text2">返回</div>
      <button @click="resetPasswordBtn">确定</button>
    </div>
  </div>
</template>

<style scoped>
  .sign-container{
    position: absolute;
    left: 0;
    right: 60%;
    top: 0;
    bottom: 0;
  }
  .sign-detail-container{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }
  .sign-detail-container h1{
    right: 12%;
    text-align: left;
    position: absolute;
    top: 16%;
    left: 12%;
    font-size: 22px;
    font-weight: bold;
  }
  .line-container{
    position: absolute;
    left: 16%;
    right: 16%;
    top: 26%;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    bottom: 42%;
  }
  .sign-line{
    height: 60px;
    width: 100%;
    margin: 4px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .sign-line img{
    height: 20px;
    margin: 0 2px 0 -2px;
    object-fit: contain;
  }
  .sign-line input{
    width: calc(100% - 35px);
    outline: none;
    border-radius: 4px;
  }
  .link-text1{
    position: absolute;
    bottom: 34%;
    right: 16%;
    color: #5471c0;
    cursor: pointer;
    font-size: 14px;
  }
  .link-text2{
    position: absolute;
    bottom: 29%;
    cursor: pointer;
    right: 16%;
    color: #5471c0;
    font-size: 14px;
  }
  .sign-detail-container button{
    position: absolute;
    bottom: 16%;
    left: 50%;
    transform: translateX(-50%);
    font-size: 18px;
    padding: 8px 0;
    border: 0;
    letter-spacing: 2px;
    color: white;
    background-color: #718acc;
    border-radius: 4px;
    box-shadow: 0 2px 8px #8fa2ee;
    transition: .3s linear;
    width: 68%;
    cursor: pointer;
  }
  .sign-detail-container button:hover{
    transform: translateX(-50%) rotateX(15deg);
    box-shadow: 0 16px 16px #8fa2ee;
  }
  .sign-divider{
    position: absolute;
    top: -16px;
    margin: 0;
  }
  .sign-in-other-container{
    position: absolute;
    bottom: 15%;
    top: 78%;
    left: 16%;
    right: 16%;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
  .sign-in-other-container img{
    height: 80%;
    cursor: pointer;
    transition: .4s;
  }
  .sign-in-other-container img:hover{
    transform: scale(1.2);
    transition: .4s;
  }

</style>